package org.jeecg.common.util.poi_tl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import lombok.Cleanup;
import lombok.SneakyThrows;

import java.io.File;
import java.io.InputStream;
import java.util.Comparator;
import java.util.List;

public class WordUtils {


    @SneakyThrows
    public static void combine(String savePath, String... needMergeFiles) {
        //保存结果文档
        File tempFile = FileUtil.createTempFile(IdUtil.getSnowflakeNextIdStr(), ".docx", FileUtil.file(savePath), true);

        Document document = new Document(FileUtil.getInputStream(FileUtil.file(tempFile)));
        //将另一个Word文档完全插入到文档中
        for (String needMergeFile : needMergeFiles) {
            @Cleanup InputStream inputStream = FileUtil.getInputStream(needMergeFile);
            document.insertTextFromStream(inputStream, FileFormat.Docx_2013);
        }
        document.saveToFile(tempFile.getAbsolutePath(), FileFormat.Docx_2013);

    }

    public static void combineByDir(String savePath, String outDir) {
        List<File> files = FileUtil.loopFiles(outDir, f -> f.getName().endsWith(".docx"));
        String[] needMergeFiles = files.stream()
                .sorted(Comparator.comparing(File::getName))
        .map(File::getAbsolutePath).distinct()
        .toArray(String[]::new);
        combine(savePath, needMergeFiles);
    }

}